import json
from pprint import pprint

from asgiref.sync import sync_to_async
from django.http import HttpResponse, HttpResponseBadRequest
from django_redis import get_redis_connection

from common.sql_constant_enum import project_status_types_Chinese, log_content_English, project_status_types_English, \
    task_type_English, task_type_Chinese, task_status_types_English, task_status_types_Chinese
from common.sql_instance_task import task_all_project_name_list_sql, task_all_execution_name_list_sql, \
    task_all_task_name_list_sql, department_person_info_list_sql, construct_sql_task_detail_list, \
    construct_sql_task_detail_with_all, construct_sql_task_summary_list, construct_sql_task_summary_list_with_all, \
    assign_to_name_list_sql, department_name_list_sql
from utils.cursorHandler import cursor, CursorHandler
from datetime import date
from common.constant import position_program_ids, map_program_ids, deliver_program_ids, OneDay, TenMinutes
from utils.normal_simple_function import serialize_json_dumps, serialize_json_date_type, redis_data_get, \
    get_self_function_name


# 项目
async def projectList(request):
    if request.method == 'GET':
        # redis缓存中获取数据
        with get_redis_connection() as redis_client:
            if redis_client.get('task_projectList') and redis_client.get('task_projectList') != '[]':
                project_info_list = json.loads(redis_client.get('task_projectList'))
            else:
                project_info_list = cursor.search_alone(task_all_project_name_list_sql)
                redis_client.set('task_projectList', json.dumps(project_info_list), ex=OneDay)

        json_returns = {
            "data": {
                "project_info_list": [
                    {
                        "id": project['id'],
                        "name": project['name'],
                    } for project in project_info_list
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')

# 迭代
async def iterationList(request):
    if request.method == 'GET':
        # redis缓存中获取数据
        with get_redis_connection() as redis_client:
            if redis_client.get('task_iterationList') and redis_client.get('task_iterationList') != '[]':
                execution_info_list = json.loads(redis_client.get('task_iterationList'))
            else:
                execution_info_list = cursor.search_alone(task_all_execution_name_list_sql)
                redis_client.set('task_iterationList', json.dumps(execution_info_list), ex=TenMinutes)

        json_returns = {
            "data": {
                "execution_info_list": [
                    {
                        "id": execution['id'],
                        "name": execution['name'],
                        "status": execution['status'],
                    } for execution in execution_info_list
                ]
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def taskList(request):
    if request.method == 'GET':
        # redis缓存中获取数据
        with get_redis_connection() as redis_client:
            if redis_client.get('task_taskList') and redis_client.get('task_taskList') != '[]':
                task_info_list = json.loads(redis_client.get('task_taskList'))
            else:
                task_info_list = cursor.search_alone(task_all_task_name_list_sql)
                redis_client.set('task_taskList', json.dumps(task_info_list), ex=TenMinutes)

        json_returns = {
            "data": {
                "task_info_list": [
                    {
                        "id": task['id'],
                        "name": task['name'],
                        "status": task['status'],
                    } for task in task_info_list
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def statusList(request):
    if request.method == 'GET':
        # status_info_list = cursor.search_alone(task_all_task_name_list_sql)

        json_returns = {
            "data": {
                "status_info_list": [
                    {
                        "name": name,
                        "status": stat,
                    } for name, stat in task_status_types_Chinese.items()
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def nameList(request):
    if request.method == 'GET':
        # 测试部门人员名称实时查询获取
        # department_person_info_list = cursor.search_alone(department_person_info_list_sql)
        # redis缓存中获取数据
        with get_redis_connection() as redis_client:
            if redis_client.get('task_nameList') and redis_client.get('task_nameList') != '[]':
                all_task_assigner_list = json.loads(redis_client.get('task_nameList'))
            else:
                all_task_assigner_list = cursor.search_alone(assign_to_name_list_sql)
                redis_client.set('task_nameList', json.dumps(all_task_assigner_list), ex=OneDay)

        json_returns = {
            "data": {
                "person_info_list": [
                    {
                        "id": each_person['id'],
                        "name": each_person['name'],
                    } for each_person in all_task_assigner_list
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def departmentNameList(request):
    if request.method == 'GET':
        # 测试部门人员名称实时查询获取
        # redis缓存中获取数据
        dept_names = redis_data_get(get_self_function_name(), department_name_list_sql)

        json_returns = {
            "data": {
                "person_info_list": [
                    {
                        "id": each_dept['id'],
                        "name": each_dept['name'],
                    } for each_dept in dept_names
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def personTaskDetailList(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        # print('-----------', params)

        # 获取请求参数
        # 项目id
        project_id = params.get("project_id", -1)
        # 迭代id(project -> sprint)
        iteration_id = params.get("iteration_id", -1)
        # 部门id
        department_id = params.get("department_id", -1)
        # 任务id
        task_id = params.get("task_id", -1)
        # 任务状态
        task_status = params.get("status", "")
        # 测试人员
        realname = params.get("name", "")
        # 记录起始时间
        date_start_time = params.get("date_start_time", "")
        # 记录结束时间
        date_end_time = params.get("date_end_time", "")
        # 分页的页码
        pageNo = params.get("pageNo", 0)
        # 页码元素个数
        pageSize = params.get("pageSize", 25)

        task_detail_sql = construct_sql_task_detail_list(
            _project_id=project_id,
            _department_id=department_id,
            _iteration_id=iteration_id,
            _task_id=task_id,
            _task_status=task_status_types_Chinese.get(task_status, None),
            _realname=realname,
            _date_start_time=date_start_time,
            _date_end_time=date_end_time,
            _pageNo=pageNo,
            _pageSize=pageSize
        )
        print(task_detail_sql)
        # person_task_detail_list = cursor.search_alone(task_detail_sql)
        person_task_detail_list = await sync_to_async(cursor.search_alone, thread_sensitive=True)(task_detail_sql)

        task_all_sql = construct_sql_task_detail_with_all(
            _project_id=project_id,
            _department_id=department_id,
            _iteration_id=iteration_id,
            _task_id=task_id,
            _task_status=task_status_types_Chinese.get(task_status, None),
            _realname=realname,
            _date_start_time=date_start_time,
            _date_end_time=date_end_time
        )
        print(task_all_sql)
        # person_task_all = cursor.search_alone(task_all_sql)
        # 尝试使用异步方法
        person_task_all = await sync_to_async(cursor.search_alone, thread_sensitive=True)(task_all_sql)

        json_returns = {
            'data': {
                "total": person_task_all[0].get('total'),
                "person_task_detail_info": [
                    {
                        # 指派人
                        "creator": each_task['creator'],
                        # 项目id
                        "project_id": each_task['project_id'],
                        # 项目名称
                        "project_name": each_task['project_name'],
                        # 迭代id
                        "execution_id": each_task['execution_id'],
                        # 迭代名称
                        "execution_name": each_task['execution_name'],
                        # 任务名称
                        "task_name": each_task['task_name'],
                        # 任务id
                        "task_id": each_task['task_id'],
                        # 预估工时
                        "task_estimate": each_task['task_estimate'],
                        # 消耗工时
                        "task_consumed": each_task['task_consumed'],
                        # 任务状态
                        "task_status": task_status_types_English.get(each_task['task_status']),
                        # 历史记录 - 记录日期
                        "log_date": serialize_json_date_type(each_task['log_date']),
                        # 时间
                        "log_record_time": serialize_json_date_type(each_task['log_record_time']),
                        # 记录人
                        "log_recorder": each_task['log_recorder'],
                        # 消耗工时
                        "log_consumed": each_task['log_consumed'],
                        # 工作内容
                        "log_content": log_content_English.get(each_task['log_content'], each_task['log_content'])
                    } for each_task in person_task_detail_list
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns),
                                content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def taskTypeList(request):
    if request.method == 'GET':

        json_returns = {
            "data": {
                "project_info_list": [
                    {
                        "type": each_type,
                        "name": each_name,
                    } for each_type, each_name in task_type_English.items()
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')

async def taskSummaryItemList(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        # print('-----------', params)

        # 获取请求参数
        # 项目id
        project_id = params.get("project_id", -1)
        # 迭代id(project -> sprint)  ----------- cancel
        iteration_id = params.get("iteration_id", -1)
        # 部门名称
        department_id = params.get("department_id", -1)
        # 任务id
        task_id = params.get("task_id", -1)
        # 任务名称
        task_name = params.get("task_name", -1)
        # 任务类型
        task_type = params.get("task_type", "")
        # 任务状态
        task_status = params.get("task_status", "")
        # 指派人员
        realname = params.get("realname", "")
        # 截止日期起始时间
        task_deadline_begin = params.get("task_deadline_begin", "")
        # 截止日期结束时间
        task_deadline_end = params.get("task_deadline_end", "")
        # 实际开始时间起始时间
        task_actual_start_date_begin = params.get("task_actual_start_date_begin", "")
        # 实际开始时间结束时间
        task_actual_start_date_end = params.get("task_actual_start_date_end", "")
        # 完成日期起始时间
        task_finish_date_begin = params.get("task_finish_date_begin", "")
        # 完成日期结束时间
        task_finish_date_end = params.get("task_finish_date_end", "")
        # 激活日期起始时间
        task_activate_date_begin = params.get("task_activate_date_begin", "")
        # 激活日期结束时间
        task_activate_date_end = params.get("task_activate_date_end", "")
        # 分页的页码
        pageNo = params.get("pageNo", 0)
        # 页码元素个数
        pageSize = params.get("pageSize", 25)


        task_summary_sql = construct_sql_task_summary_list(
            _project_id=project_id,
            _iteration_id=iteration_id,
            _department_id=department_id,
            _task_id=task_id,
            _task_name=task_name,
            _task_type=task_type_Chinese.get(task_type),
            _task_status=task_status_types_Chinese.get(task_status),
            _task_deadline_begin=task_deadline_begin,
            _task_deadline_end=task_deadline_end,
            _task_actual_start_date_begin=task_actual_start_date_begin,
            _task_actual_start_date_end=task_actual_start_date_end,
            _task_finish_date_begin=task_finish_date_begin,
            _task_finish_date_end=task_finish_date_end,
            _task_assign_to=realname,
            _task_activate_date_begin=task_activate_date_begin,
            _task_activate_date_end=task_activate_date_end,
            _page_no=pageNo,
            _page_size=pageSize
        )
        print(task_summary_sql)
        # person_task_summary_list = cursor.search_alone(task_summary_sql)
        person_task_summary_list = await sync_to_async(cursor.search_alone, thread_sensitive=True)(task_summary_sql)

        task_item_all_sql = construct_sql_task_summary_list_with_all(
            _project_id=project_id,
            _iteration_id=iteration_id,
            _department_id=department_id,
            _task_id=task_id,
            _task_name=task_name,
            _task_type=task_status_types_Chinese.get(task_type),
            _task_status=task_type_Chinese.get(task_status),
            _task_deadline_begin=task_deadline_begin,
            _task_deadline_end=task_deadline_end,
            _task_actual_start_date_begin=task_actual_start_date_begin,
            _task_actual_start_date_end=task_actual_start_date_end,
            _task_finish_date_begin=task_finish_date_begin,
            _task_finish_date_end=task_finish_date_end,
            _task_assign_to=realname,
            _task_activate_date_begin=task_activate_date_begin,
            _task_activate_date_end=task_activate_date_end
        )
        print(task_item_all_sql)
        # person_task_all = cursor.search_alone(task_item_all_sql)

        # 尝试使用异步方法
        person_task_all = await sync_to_async(cursor.search_alone, thread_sensitive=True)(task_item_all_sql)

        json_returns = {
            'data': {
                "total": person_task_all[0].get('total'),
                "person_task_detail_info": [
                    {
                        # 指派人
                        "creator": each_task['realname'],
                        # 项目id
                        "project_id": each_task['project_id'],
                        # 项目名称
                        "project_name": each_task['project_name'],
                        # 迭代id
                        "execution_id": each_task['execution_id'],
                        # 迭代名称
                        "execution_name": each_task['execution_name'],
                        # 任务名称
                        "task_name": each_task['task_name'],
                        # 任务id
                        "task_id": each_task['task_id'],
                        # 预估工时
                        "task_estimate": each_task['task_estimate'],
                        # 消耗工时
                        "task_consumed": each_task['task_consumed'],
                        # 任务类型
                        "task_type": task_type_English.get(each_task['task_type']),
                        # 任务状态
                        "task_status": task_status_types_English.get(each_task['task_status']),
                        # 最后修改日期
                        "task_last_edited_date": serialize_json_date_type(each_task['task_last_edited_date']),
                        # 截止日期
                        "task_deadline": serialize_json_date_type(each_task['task_deadline']),
                        # 预期开始时间
                        "task_plan_start": serialize_json_date_type(each_task['task_plan_start']),
                        # 实际开始
                        "task_actual_start": serialize_json_date_type(each_task['task_actual_start']),
                        # 预计完成
                        "task_plan_finish_date": serialize_json_date_type(each_task['task_plan_finish_date']),
                        # 实际完成
                        "task_finish_date": serialize_json_date_type(each_task['task_finish_date']),
                        # 激活日期
                        "task_activate_date": serialize_json_date_type(each_task['task_activate_date']),
                    } for each_task in person_task_summary_list
                ]
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns),
                                content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')




